<template>
	<view class="plan_page">
		<view class="header">
			<view @click="toggleCalendar" class="month-display">{{ getChineseMonth(currentDate.getMonth() + 1) }}</view>
			<view @click="toggleMonthSelection" v-if="showCalendar" class="change-month-button">更换月份</view>
		</view>
		<!-- 日历浮窗 -->
		<view v-if="showCalendar" class="calendar-container">
			<view class="calendar-popup">

				<!-- 月份选择 -->
				<view v-if="isMonthSelection" class="month-selection">
					<view v-for="(month, index) in chineseMonths" :key="index"
						:class="['calendar-month', { selected: index === currentDate.getMonth() }]"
						@click="selectMonth(index)">
						{{ month }}
					</view>
				</view>
				<!-- 日期选择 -->
				<view v-else class="calendar">
					<!-- 日历头部 -->
					<view class="calendar-header">
						<view v-for="day in daysOfWeek" :key="day" class="calendar-day">{{ day }}</view>
					</view>

					<!-- 日历内容 -->
					<view class="calendar-body">
						<view v-for="(week, weekIndex) in calendar" :key="weekIndex" class="calendar-week">
							<view v-for="(date, dateIndex) in week" :key="dateIndex"
								:class="['calendar-date', { selected: isSelectedDate(date) }]"
								@click="selectDate(date)">
								{{ date }}
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="overlay" @click="toggleCalendar"></view>
		</view>

		<view class="now_week">
			<!-- <view class="day_item" v-for="(e,i) in showDateList" :key="i">
				<view>
					{{e.dayOfWeek}}
				</view>
			</view> -->
			<scroll-view class="day_scroll" scroll-x>
				<view class="day_item" v-for="(e, i) in showDateList" :key="i" @tap="selectPlanDate(e)">
					<view :class="{'selected': e.date === dateToString(currentDate)}">
						{{ e.dayOfWeek }}
					</view>
				</view>
			</scroll-view>
		</view>
		<!-- 任务事项 -->
		<scroll-view class="plan_content" scroll-y :scroll-top="scrollTop" scroll-with-animation @scroll="scroll">
			<view class="plan_list">
				<view class="plan_item" v-for="(hour, index) in hours" :key="index"
					@tap="createOrUpdateTaskHandle(hour)">
					<text class="item_time">{{hour}}</text>
					<!-- <view class="item_text">
						<view class="text_content" @tap="createTaskHandle(e)">
							<text class="text_time">9:00-10:00</text>
							<text>去城建院交材料</text>
						</view>
					</view> -->
					<!-- v-for="item in  timeBlocks.filter(block => block.startHour === hour)" :key="item.id" -->
					<view class="item_text">
						<view v-for="item in  timeBlocks.filter(block => block.startHour === hour)" :key="item.id"
							class="block" :class="{ 'completed': item.complete === 1 }" :style="getBlockStyle(item)">
							<view v-if="item.startHour === hour" class="text_content"
								@tap.stop="createOrUpdateTaskHandle(hour, item)" @touchstart="handleTouchStart"
								@touchmove="handleTouchMove" @touchend="handleTouchEnd(item.id)">
								<text
									class="text_time">{{showTimeFormat(item.startTime)}}-{{showTimeFormat(item.endTime)}}</text>
								<text>{{ item.name }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<clipTabbar curIndex="0"></clipTabbar>
		<clipRemind></clipRemind>
		<!-- <planForm></planForm> -->
		<planModal v-if="showForm" :planFormData="planFormData" @close="closePlanModalHandle" />
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		nextTick
	} from "vue";
	import {
		onShow
	} from '@dcloudio/uni-app';
	import {
		apiQueryPlan,
		apiCompletePlan
	} from "@/requestApi/plan.js";
	//import planForm from '@/pages/plan/components/planForm.vue';
	import planModal from '@/pages/plan/components/planModal.vue';
	import {
		canDrawOverlays,
	} from "@/utils/remindFn.js"
	// Date转字符串
	const dateToString = (date) => {
		return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
	}

	const showCurrentDateList = ref([]);
	const checkedDate = ref('');
	const planFormData = ref({});
	const showForm = ref(false);
	const scrollTop = ref(0); // 滚动条位置，距离顶部为0
	const oldScrollTop = ref(0);

	const showCalendar = ref(false);
	const isMonthSelection = ref(false);
	const showChangeMonthButton = ref(false);
	const calendar = ref([]);
	const currentDate = ref(new Date());
	const currentDefaultDate = ref(new Date());
	const selectedDate = ref(currentDate.value.getDate());
	const daysOfWeek = ['一', '二', '三', '四', '五', '六', '日'];
	const chineseMonths = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];

	const showDateList = ref([]);
	const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
	const touchStartX = ref(0);
	const touchEndX = ref(0);

	const toggleCalendar = () => {
		showCalendar.value = !showCalendar.value;
		isMonthSelection.value = false;
		if (showCalendar.value) {
			selectedDate.value = currentDate.value.getDate();
		}
	};

	const toggleMonthSelection = () => {
		isMonthSelection.value = !isMonthSelection.value;
		// 当点击了更换月份
	};

	const scroll = (e) => {
		//记录滑动位置
		oldScrollTop.value = e.detail.scrollTop
	}

	const scape = ref(0);

	const scrollToTop = () => {
		// 首先根据timeBlocks获取第一个有值的时间段,
		let firstTime = 0;
		if (timeBlocks.value && timeBlocks.value.length > 0) {
			const firstBlock = timeBlocks.value.find(item => item.complete === 0);
			firstTime = firstBlock ? firstBlock.startHour : 0;
		}

		// 然后获取该时间段的所处高度
		nextTick(() => {
			scrollTop.value = firstTime * scape.value;
			// scrollTop.value = 540;
			console.log('hhh', firstTime, scape.value, scrollTop.value)
		});
		// scrollTop.value = oldScrollTop.value
		// nextTick(() => {
		// 	scrollTop.value = 0
		// });
	};

	const selectMonth = (month) => {
		currentDate.value.setMonth(month);
		if (month === currentDefaultDate.value.getMonth()) {
			selectedDate.value = currentDefaultDate.value.getDate();
		} else {
			selectedDate.value = 1;
		}
		generateCalendar(currentDate.value.getFullYear(), month);
		isMonthSelection.value = false;
	};

	// 日期的选择
	const selectDate = (date) => {
		//console.log('看这里日期的选择:', date, selectedDate.value, currentDate.value);
		if (date) {
			currentDate.value.setDate(date);
			showDateList.value = getDateList(dateToString(currentDate.value));
			selectedDate.value = date;
			handleDateChange(dateToString(currentDate.value));
			showCalendar.value = false; // 选择日期后关闭浮窗
		}
	};

	const generateCalendar = (year, month) => {
		const firstDayOfMonth = new Date(year, month, 1).getDay();
		const daysInMonth = new Date(year, month + 1, 0).getDate();
		const calendarArray = [];
		let week = [];

		// 从周一开始，所以需要调整 firstDayOfMonth
		const adjustedFirstDay = firstDayOfMonth === 0 ? 6 : firstDayOfMonth - 1;

		// 填充第一周的空白
		for (let i = 0; i < adjustedFirstDay; i++) {
			week.push('');
		}

		// 填充日期
		for (let day = 1; day <= daysInMonth; day++) {
			week.push(day);
			if (week.length === 7) {
				calendarArray.push(week);
				week = [];
			}
		}

		// 填充最后一周的空白
		while (week.length < 7) {
			week.push('');
		}
		calendarArray.push(week);

		calendar.value = calendarArray;
	};

	const isSelectedDate = (date) => {
		return date === selectedDate.value && date !== '';
	};

	const getChineseMonth = (month) => {
		return chineseMonths[month - 1];
	};

	const toggleChangeMonthButton = () => {
		showChangeMonthButton.value = !showChangeMonthButton.value;
	};



	const getDateList = (centerDate) => {
		console.log('centerDate', centerDate)
		const dateList = [];
		const baseDate = new Date(centerDate);
		baseDate.setDate(baseDate.getDate() - 1); // 显示三天，中心日期在中间，所以要减一天

		for (let i = 0; i < 3; i++) {
			const date = new Date(baseDate);
			date.setDate(baseDate.getDate() + i);
			const dayOfWeek = weekdays[date.getDay()];
			const formattedDate =
				`${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
			dateList.push({
				date: formattedDate,
				dayOfWeek: dayOfWeek,
			});
		}
		return dateList;
	};

	// 横向滑动选择日期
	const selectPlanDate = (date) => {
		// console.log('看这里 横向滑动选择日期', date, selectedDate.value, currentDate.value);
		showDateList.value = getDateList(date.date);
		currentDate.value = new Date(date.date);
		selectedDate.value = currentDate.value.getDate();
		handleDateChange(dateToString(currentDate.value));
	};

	const handleDateChange = (selectedDate) => {
		// 在这里处理日期选择后的逻辑
		// console.log('Selected date:', selectedDate);
		queryPlanHandle(selectedDate);
	};

	// 查询任务
	const queryPlanHandle = (data) => {
		let token = uni.getStorageSync("token")
		if (!token) {
			return uni.navigateTo({
				url: '/pages/login/main'
			});
		} else {
			apiQueryPlan(data).then(res => {
				if (res.code == 1 && res.data) {
					const planList = res.data.planList;
					console.log('planList', planList)
					calculateTimeBlocks(planList);
				} else {}
			}).catch(err => {
				console.log(err, 'err')
			})
		}
	}

	// 展示时间格式化
	const showTimeFormat = (time) => {
		const [hours, minutes] = time.split(':');
		const formattedHours = parseInt(hours, 10);
		return `${formattedHours}:${minutes}`;
	}

	// 传值时间格式化
	const transTimeFormat = (time) => {
		if (typeof time === 'number') {
			return time.toString().padStart(2, '0') + ':00';
		} else if (typeof time === 'string') {
			if (time.length === 8) {
				return time.slice(0, 5);
			}
		}
		return time;
	}



	// 创建当日任务
	const createOrUpdateTaskHandle = (hour, data) => {
		console.log("data", data);
		planFormData.value = {
			hour: hour,
			date: selectedDate.value,
			id: data ? data.id : null,
			name: data ? data.name : '',
			planDetail: data ? data.planDetail : '',
			planType: data ? data.planType : 3,
			priority: data ? data.priority : 1,
			loopAuto: data ? data.loopAuto : false,
			loopType: data ? data.loopType : 0,
			loopCustom: data ? data.loopCustom : '',
			tags: data ? data.tags : null,
			remindAuto: data ? data.remindAuto : true,
			remindWay: data ? data.remindWay : 1,
			remindBeforeSecond: data ? data.remindBeforeSecond : 0,
			startDate: data ? data.startDate : dateToString(currentDate.value),
			endDate: data ? data.endDate : null,
			startTime: data ? transTimeFormat(data.startTime) : transTimeFormat(hour),
			endTime: data ? transTimeFormat(data.endTime) : transTimeFormat(++hour),
		};

		console.log("planFormData", planFormData.value);
		showForm.value = true;
		canDrawOverlays()
	};

	const closePlanModalHandle = (data) => {
		console.log('iscreate===>', data, data.isCreate);
		if (data && data.isCreate) {
			console.log('进来了吗===>', data, data.isCreate, selectedDate.value);
			queryPlanHandle(dateToString(currentDate.value));
		}
		showForm.value = false;
	}

	const hours = Array.from({
		length: 24
	}, (_, i) => i);

	// 测试数据
	// const items = ref([{
	// 		id: 4,
	// 		name: "测试事项0",
	// 		"startDate": "2024-07-10",
	// 		startTime: "08:55:00",
	// 		endTime: "12:00:00",
	// 		complete: 0,
	// 	},
	// 	{
	// 		"id": 6,
	// 		"name": "0710测试",
	// 		"planDetail": "测试内容",
	// 		"planType": 3,
	// 		"priority": 1,
	// 		"loopAuto": false,
	// 		"loopType": null,
	// 		"loopCustom": null,
	// 		"tags": null,
	// 		"remindAuto": true,
	// 		"remindWay": 1,
	// 		"remindBeforeSecond": 0,
	// 		"startDate": "2024-07-10",
	// 		"endDate": null,
	// 		"startTime": "09:00:00",
	// 		"endTime": "10:00:00",
	// 		"complete": 0
	// 	}
	// ]);

	const timeBlocks = ref([]);

	const calculateTimeBlocks = async (items) => {
		const currentDateStr = dateToString(currentDate.value);
		console.log('默认当天时间', currentDateStr);
		timeBlocks.value = items.filter(item => currentDateStr === item.startDate)
			.map((item) => {
				const [startHour, startMinute] = item.startTime.split(':').map(Number);
				const [endHour, endMinute] = item.endTime.split(':').map(Number);
				return {
					...item,
					startHour,
					startMinute,
					endHour,
					endMinute,
					//color: `#${Math.floor(Math.random() * 16777215).toString(16)}`
				};
			});
		await nextTick();
		if (!scape.value) {
			const query = uni.createSelectorQuery().in(this);
			query.selectAll('.item_text').boundingClientRect(data => {
				if (data && data[0] && data[1]) {
					scape.value = data[1].top - data[0].top;
				}
				scrollToTop();
			}).exec();
		} else {
			scrollToTop();
		}

	};

	// 处理任务的手指滑动
	const handleTouchStart = (event) => {
		touchStartX.value = event.touches[0].clientX;
	};

	const handleTouchMove = (event) => {
		touchEndX.value = event.touches[0].clientX;
	};

	const handleTouchEnd = (planId) => {
		const deltaX = touchEndX.value - touchStartX.value;
		console.log('滑动距离', deltaX, '处理Id', planId);
		if (deltaX > 50) {
			// 右滑
			onSwipeRight(planId);
		} else if (deltaX < -50) {
			// 左滑
			onSwipeLeft(planId);
		}
	};

	// 右滑完成
	const onSwipeRight = (planId) => {
		const nowDateTime = new Date();
		const data = {
			planId: planId,
			operatorDate: nowDateTime.toISOString().split('T')[0],
			complete: 1
		}
		// 处理右滑的逻辑
		apiCompletePlan(data).then(res => {
			console.log('完成任务返回', res);
			if (res.code == 1 && res.data) {
				const currentDateValue = currentDate.value;
				const date =
					`${currentDateValue.getFullYear()}-${(currentDateValue.getMonth() + 1).toString().padStart(2, '0')}-${currentDateValue.getDate().toString().padStart(2, '0')}`;
				showDateList.value = getDateList(date);
				queryPlanHandle(date);
			} else {}
		}).catch(err => {
			console.log(err, 'err')
		})
	};

	// 左滑取消完成
	const onSwipeLeft = (planId) => {
		const nowDateTime = new Date();
		const data = {
			planId: planId,
			operatorDate: nowDateTime.toISOString().split('T')[0],
			complete: 0
		}
		// 处理右滑的逻辑
		apiCompletePlan(data).then(res => {
			console.log('取消完成任务返回', res);
			if (res.code == 1 && res.data) {
				const currentDateValue = currentDate.value;
				const date =
					`${currentDateValue.getFullYear()}-${(currentDateValue.getMonth() + 1).toString().padStart(2, '0')}-${currentDateValue.getDate().toString().padStart(2, '0')}`;
				showDateList.value = getDateList(date);
				queryPlanHandle(date);
			} else {}
		}).catch(err => {
			console.log(err, 'err')
		})
	};

	const getBlockStyle = (item, hour) => {
		return {
			backgroundColor: item.color,
			height: '50px',
			marginBottom: '5px',
			display: 'flex',
			alignItems: 'center',
			justifyContent: 'center',
			color: '#fff',
			borderRadius: '5px',
		};
	};
	onShow(() => {
		let token = uni.getStorageSync("token");
		if (!token) {
			return uni.navigateTo({
				url: '/pages/login/main',
			});
		}
		const currentDateValue = currentDate.value;
		const date =
			`${currentDateValue.getFullYear()}-${(currentDateValue.getMonth() + 1).toString().padStart(2, '0')}-${currentDateValue.getDate().toString().padStart(2, '0')}`;
		showDateList.value = getDateList(date);
		selectedDate.value = currentDateValue.getDate();
		queryPlanHandle(date);
		generateCalendar(currentDateValue.getFullYear(), currentDateValue.getMonth())
	});
	// onMounted(() => {
	// 	let token = uni.getStorageSync("token")
	// 	// console.log(token)
	// 	if (!token) {
	// 		console.log('3333')
	// 		return uni.navigateTo({
	// 			url: '/pages/login/main',
	// 		});
	// 	}

	// 	const currentDateValue = currentDate.value;
	// 	const date =
	// 		`${currentDateValue.getFullYear()}-${(currentDateValue.getMonth() + 1).toString().padStart(2, '0')}-${currentDateValue.getDate().toString().padStart(2, '0')}`;
	// 	showDateList.value = getDateList(date);
	// 	selectedDate.value = currentDateValue.getDate();
	// 	queryPlanHandle(date);

	// 	generateCalendar(currentDateValue.getFullYear(), currentDateValue.getMonth())
	// });
</script>

<style scoped lang="less">
	.plan_page {
		box-sizing: border-box;
		padding: 88rpx 57rpx 227rpx;
		// max-height: 100vh;
		display: flex;
		flex-direction: column;
		align-items: center;

		.header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			width: 100%;
			padding: 10px;
			border-radius: 5px;
			margin-bottom: 20px;
			position: relative;
		}

		.month-display {
			font-size: 64rpx;
			line-height: 88rpx;
			color: #343A40;
		}

		.change-month-button {
			padding: 5px 10px;
			cursor: pointer;
		}

		.calendar-container {
			position: relative;
			width: 100%;
		}

		.calendar-popup {
			position: absolute;
			top: 100%;
			left: -8rpx;
			width: 102%;
			max-width: 500px;
			height: 50vh;
			background-color: white;
			border-bottom-left-radius: 40rpx;
			border-bottom-right-radius: 40rpx;
			//box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
			overflow: hidden;
			z-index: 10;
		}

		.overlay {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100vh;
			background-color: rgba(0, 0, 0, 0.5);
			z-index: 5;
		}

		.calendar {
			display: flex;
			flex-direction: column;
			padding: 20px;
		}

		.calendar-header {
			display: flex;
			justify-content: space-around;
			font-weight: bold;
			margin-bottom: 10px;
		}

		.calendar-body {
			display: flex;
			flex-direction: column;
		}

		.calendar-week {
			display: flex;
			justify-content: space-around;
		}

		.calendar-day,
		.calendar-date {
			width: 40px;
			height: 40px;
			display: flex;
			align-items: center;
			justify-content: center;
			cursor: pointer;
		}

		.calendar-date.today {
			background-color: #007aff;
			color: white;
			border-radius: 5px;
		}

		.calendar-date.selected {
			background-color: #007aff;
			color: white;
			border-radius: 5px;
		}

		.month-selection {
			display: flex;
			flex-wrap: wrap;
			padding: 20px;
		}

		.calendar-month {
			width: 33.33%;
			height: 40px;
			display: flex;
			align-items: center;
			justify-content: center;
			cursor: pointer;
		}

		.calendar-month.selected {
			background-color: #007aff;
			color: white;
			border-radius: 5px;
		}

		.now_month {
			font-size: 64rpx;
			line-height: 88rpx;
			color: #343A40;
		}

		.now_week {
			display: flex;
			align-items: center;
			// width: 100%;
			// justify-content: space-between;
			// padding-top: 44rpx;
			// padding-bottom: 14rpx;
			// box-sizing: border-box;

			// .day_item {
			// 	text-align: center;
			// 	font-size: 32rpx;
			// 	height: 46rpx;
			// 	flex: 1;
			// 	color: #343A40;
			// }
		}

		.day_scroll {
			display: flex;
			flex-direction: row;
			overflow-x: scroll;
			white-space: nowrap;
		}

		.day_item {
			display: inline-block;
			text-align: center;
			padding: 10px;
			min-width: 100px;

			.selected {
				font-weight: bold;
				// color: blue;
			}
		}

		.plan_content {
			height: calc(100vh - 530rpx);
			border: 2.3rpx solid #DEE2E6;
			border-radius: 46rpx;

			.plan_list {
				display: flex;
				width: 100%;
				flex-direction: column;

				.plan_item {
					display: flex;
					align-items: center;
					box-sizing: border-box;
					padding: 8rpx 48rpx 0 28rpx;
					min-height: 92rpx;

					.item_time {
						display: inline-block;
						min-width: 76rpx;
						font-size: 28rpx;
						font-weight: 400;
						letter-spacing: 0rpx;
						color: #212529;
						text-align: left;
						vertical-align: top;
					}

					.item_text {
						width: 520px;
						min-height: 92rpx;
						box-sizing: border-box;
						border-bottom: 2.3rpx solid #E9ECEF;
						display: flex;
						flex-direction: column;
						// align-items: flex-start;
						justify-content: center;
						align-items: center;

						.text_content {
							display: flex;
							align-items: center;
							width: 520rpx;
							height: 66rpx;
							opacity: 1;
							border-radius: 16rpx;
							background: rgba(239, 111, 108, 1);
							/** 文本1 */
							font-size: 28rpx;
							font-weight: 400;
							letter-spacing: 0rpx;
							color: rgba(255, 245, 245, 1);
							vertical-align: top;

							.text_time {
								padding: 0 50rpx 0 22rpx;
							}
						}
					}

					.plan_item:last-child {
						.item_text {
							//border-bottom: none;
						}
					}
				}

				.completed {
					position: relative;
				}

				.completed::before {
					content: '';
					position: absolute;
					left: 10px;
					right: 10px;
					top: 50%;
					height: 1px;
					background-color: black;
					transform: translateY(-50%);
				}

			}
		}
	}
</style>